var getCookie = function getCookie(key) {
    var arr1 = document.cookie.split('; ')
    //["user1=111asdasd", "user2=222gfhft", "user3=333wwwaa"]
    for (var i = 0; i < arr1.length; i++) {
        var arr2 = arr1[i].split('=') //['user1','111asdasd']
        if (arr2[0] === key) {
            // 对数据进行解码并返回
            return unescape(arr2[1])
        }
    }
    return null
}
var bigNav1 = [];
var midNav1 = [];
var smaNav1 = [];
$.post('./json/goods.json', {}, function (data) {
    for (key in data) {
        bigNav1.push(key)
        var midTmp = []
        for (key1 in data[key]) {
            midTmp.push(key1)
            var smaTmp = []
            for (key2 in data[key][key1]) {
                smaTmp.push(key2)
            }
            var dd = {}
            dd[key1] = smaTmp
            smaNav1.push(dd)
        }
        var dd = {}
        dd[key] = midTmp
        midNav1.push(dd)
    }
});
let count = 0 // 数据总条数
let pages = 0 // 数据总页数
let current = 1 // 当前页码
let size = 5 // 每页条数
let typestack = [];

function getPageData(page, size) { //获取分页数据
    // $.ajax({
    // 	url: "./php/search.php",
    // 	type: 'post',
    // 	data: {
    // 		page: page,
    // 		size: size,
    //         ways:way
    // 	},
    // 	dataType: 'json',
    // 	success: function (data){
    count = typestack.length
    pages = Math.ceil(typestack.length / size)
    var dataarr = [];
    for (var j = (page - 1) * size; j < ((page - 1) * size + size); j++) {
        if (typestack[j]) {
            dataarr.push(typestack[j])
        } else {
            break;
        }
    }
    // 根据数据渲染页面
    renderTable(dataarr)
    // 渲染分页
    renderPage(current, pages)
    $('.find b').html(count)
    // 显示总条数
    // $('.number').text(count)


    // 	}
    // })
}

function renderTable(data) { //渲染页面
    let str = ''
    $.each(data, function (index, item) {
        str += `
        <div class="listone">
        <span>${item['goodsname']}</span>
        <span>${item['id']}</span>
        <span>${item['bigNav']}</span>
        <span>${item['midNav']}</span>
        <span>${item['smaNav']}</span>
        <span>${item['mat']}</span>
        <span>${item['price1']}</span>
        <span>${item['price2']}</span>
        <span><img src='${item['url']}'></span>
        <span><b onclick="editThis(this)">编辑</b>&emsp;<b onclick="deleteThis(this)">删除</b></span>
    </div>
        `
    })
    $(".datalist").html(str)
}
//编辑
function editThis(el) {
    var el = el.parentNode.parentNode
    el.innerHTML = `
    <span><input type='text' value='${el.children[0].innerText}'></span>
    <span>${el.children[1].innerText}</span>
    <span>
    <select name="" id="" value="${el.children[2].innerText}">
    <option value="${el.children[2].innerText}">
    ${el.children[2].innerText}
    </option>
    </select>
    </span>
    <span>
    <select name="" id="" value="${el.children[3].innerText}">
    <option value="${el.children[3].innerText}">
    ${el.children[3].innerText}
    </option>
    </select>
    </span>
    <span>
    <select name="" id="" value="${el.children[4].innerText}">
    <option value="${el.children[4].innerText}">
    ${el.children[4].innerText}
    </option>
    </select>
    </span>
    <span><input type='text' value='${el.children[5].innerText}'></span>
    <span><input type='text' value='${el.children[6].innerText.split("￥")[1]}'></span>
    <span><input type='text' value='${el.children[7].innerText.split("￥")[1]}'></span>
    <span>${el.children[8].innerHTML}</span>
    <span><b onclick="yes(this)">确认</b></span>
    `
    var strbig = `<select name="" id="" value="${el.children[2].innerText}" onchange="bigNavChange(this)">`
    for (var i = 0; i < bigNav1.length; i++) {
        strbig += `<option value="${bigNav1[i]}">
        ${bigNav1[i]}
        </option>`
    }
    strbig += `</select>`
    el.children[2].innerHTML = strbig

    for (var i = 0; i < midNav1.length; i++) {
        for (key in midNav1[i]) {
            if (key == el.children[2].children[0].value) {
                var strmid = `<select name="" id="" value="${el.children[3].innerText}" onchange="midNavChange(this)">`
                for (var j = 0; j < midNav1[i][key].length; j++) {
                    strmid += `<option value="${midNav1[i][key][j]}">
                    ${midNav1[i][key][j]}
                    </option>`
                }
                strmid += `</select>`
                el.children[3].innerHTML = strmid
            }
        }
    }
    for (var i = 0; i < smaNav1.length; i++) {
        for (key in smaNav1[i]) {
            if (key == el.children[3].children[0].value) {
                var strsma = `<select name="" id="" value="${el.children[4].children[0].value}" onchange="midNavChange(this)">`
                for (var j = 0; j < smaNav1[i][key].length; j++) {
                    strsma += `<option value="${smaNav1[i][key][j]}">
                    ${smaNav1[i][key][j]}
                    </option>`
                }
                strsma += `</select>`
                el.children[4].innerHTML = strsma
            }
        }
    }
}
// 删除
function deleteThis(el) {
    var el = el.parentNode.parentNode
    var elid = el.children[1].innerText
    $.post('./php/backstage.php', {
        id: elid,
        way: 'delete',
    }, function (data) {
        el.remove()
        location.reload();
    });
    // el.remove()
}
// bigNav1发生改变
function bigNavChange(el) {
    var el = el.parentNode.parentNode
    var va = el.children[2].children[0].value
    for (var i = 0; i < midNav1.length; i++) {
        for (key in midNav1[i]) {
            if (key == va) {
                var strmid = `<select name="" id="" value="${el.children[3].children[0].value}" onchange="midNavChange(this)">`
                for (var j = 0; j < midNav1[i][key].length; j++) {
                    strmid += `<option value="${midNav1[i][key][j]}">
                    ${midNav1[i][key][j]}
                    </option>`
                }
                strmid += `</select>`
                el.children[3].innerHTML = strmid
            }
        }
    }
    midNavChange(el.children[3].children[0])
}
// midNav1发生改变
function midNavChange(el) {
    var el = el.parentNode.parentNode
    var va = el.children[3].children[0].value
    for (var i = 0; i < smaNav1.length; i++) {
        for (key in smaNav1[i]) {
            if (key == va) {
                var strsma = `<select name="" id="" value="${el.children[4].children[0].value}" onchange="midNavChange(this)">`
                for (var j = 0; j < smaNav1[i][key].length; j++) {
                    strsma += `<option value="${smaNav1[i][key][j]}">
                    ${smaNav1[i][key][j]}
                    </option>`
                }
                strsma += `</select>`
                el.children[4].innerHTML = strsma
            }
        }
    }

}
// 点击确认
function yes(el){
    var el = el.parentNode.parentNode
    if(parseFloat(el.children[6].children[0].value)&&parseFloat(el.children[7].children[0].value)){
        $.post('./php/backstage.php', {
            name: getCookie("username"),
            way: 'update',
            id:el.children[1].innerText,
            goodsname:el.children[0].children[0].value,
            bigNav:el.children[2].children[0].value,
            midNav:el.children[3].children[0].value,
            smaNav:el.children[4].children[0].value,
            mat:el.children[5].children[0].value,
            price1:el.children[6].children[0].value,
            price2:el.children[7].children[0].value,
        }, function (data) {
        
        });
        el.innerHTML = `
        <span>${el.children[0].children[0].value}</span>
        <span>${el.children[1].innerText}</span>
        <span>${el.children[2].children[0].value}</span>
        <span>${el.children[3].children[0].value}</span>
        <span>${el.children[4].children[0].value}</span>
        <span>${el.children[5].children[0].value}</span>
        <span>￥${parseFloat(el.children[6].children[0].value).toFixed(2)}</span>
        <span>￥${parseFloat(el.children[7].children[0].value).toFixed(2)}</span>
        <span>${el.children[8].innerHTML}</span>
        <span><b onclick="editThis(this)">编辑</b>&emsp;<b onclick="deleteThis(this)">删除</b></span>
        `
    }else{
        alert('价格必须为数字')
    }

}


function renderPage(current, page) { // 渲染分页
    var str = ''
    if (page <= 8) {
        for (var i = 1; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    } else if (page > 8 && (current > 4 && current < page - 3)) {
        for (var i = 1; i <= 2; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = parseInt(current) - 1; i <= parseInt(current) + 1; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = page - 1; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    } else if (page > 8 && (current < 4)) {
        for (var i = 1; i <= 4; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = page - 1; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    } else if (page > 8 && (current == 4)) {
        for (var i = 1; i <= 5; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = page - 1; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    } else if (page > 8 && (current == page - 3)) {
        for (var i = 1; i <= 2; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = page - 4; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    } else if (page > 8 && (current > page - 3)) {
        for (var i = 1; i <= 2; i++) {
            str += '<i>' + i + '</i>'
        }
        str += '<i>' + '...' + '</i>'
        for (var i = page - 3; i <= page; i++) {
            str += '<i>' + i + '</i>'
        }
    }
    $('.nums').html(str)
    if (current >= 5 && current < page - 2 && page > 8) {
        $('.nums i').eq(4).addClass('active')
    } else if (current >= page - 2 && page > 8) {
        $('.nums i').eq(7 - (page - current + 1)).addClass('active').siblings().removeClass('active')
    } else {
        $('.nums i').eq(current - 1).addClass('active').siblings().removeClass('active')
    }

}

// 点击上一页
$('.prev').click(function () {
    current--
    if (current <= 0) {
        current = 1
        return
    }
    getPageData(current, size)
    if (current >= 5) {

    } else {
        $('.nums i').eq(current - 1).addClass('active').siblings().removeClass('active')
    }
})

// 点击下一页
$('.next').click(function () {
    current++
    if (current > pages) {
        current = pages
        return
    }
    getPageData(current, size)
    if (current >= 5) {

    } else {
        $('.nums i').eq(current - 1).addClass('active').siblings().removeClass('active')
    }



})

// 点击页码
$('.nums').on('click', 'i', function () {
    current = $(this).text()
    getPageData(current, size)
    if (current >= 5) {

    } else {
        $('.nums i').eq(current - 1).addClass('active').siblings().removeClass('active')
    }
})

// 跳转到指定页
$('.go em').click(function () {
    current = $('.ipt').val()
    getPageData(current, size)
    if (current >= 5) {

    } else {
        $('.nums i').eq(current - 1).addClass('active').siblings().removeClass('active')
    }
})

$('.welcome span').html(`欢迎您：${getCookie("username")} ! `)
$.post('./php/backstage.php', {
    name: getCookie("username"),
    way: 'searchall'
}, function (data) {
    data = JSON.parse(data)
    if(data[0]){
        typestack = data
        getPageData(current, size)
    }else{
        var str = `<div style="height:50px;text-align:center;font-size:25px;line-height:50px">您还没有商品，快去上架吧</div>`
        $(".datalist")[0].innerHTML=str
    }

});
$('.operate button').on('click',function(){
    $('.datatable')[0].style.display='none'
    $('.addgoods')[0].style.display='block'
})
function addg(el){
    var el = el.parentNode.parentNode
    var goodsname = el.children[0].children[0].value
    var bigNav = el.children[2].children[0].value
    var midNav = el.children[3].children[0].value
    var smaNav = el.children[4].children[0].value
    var mat = el.children[5].children[0].value
    var price1 = el.children[6].children[0].value
    var price2 = el.children[7].children[0].value
    var jpg = el.children[8].children[0].children[0].files[0]
    if(goodsname&&bigNav&&midNav&&smaNav&&mat&&price1&&price2&&jpg){
        
    }else{
        alert("请确定所有数据")
        return
    }
    var formData = new FormData(el.children[8].children[0]);
    formData.append("file",jpg);
    formData.append("way","addgoods")
    formData.append("goodsname",goodsname)
    formData.append("bigNav",bigNav)
    formData.append("midNav",midNav)
    formData.append("smaNav",smaNav)
    formData.append("mat",mat)
    formData.append("price1",price1)
    formData.append("price2",price2)
    formData.append('name',getCookie("username"))
    $.ajax({
        url: './php/backstage.php', 
        type:'POST',
        cache: false, 
        processData: false,
        contentType: false,
        data: formData,
        success: function(data){
            location.reload();
        },
        error: function(err) {
 
        }
        })

}
